package com.yanwq.sayhi.controller.article.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yanwq.sayhi.R;
import com.yanwq.sayhi.base.BaseToolbarActivity;
import com.yanwq.sayhi.common.client.OkJsonObjectResponseCallback;
import com.yanwq.sayhi.common.client.OkRequestParams;
import com.yanwq.sayhi.common.client.OkRestClient;
import com.yanwq.sayhi.common.constant.CacheConstant;
import com.yanwq.sayhi.common.constant.RegexConstant;
import com.yanwq.sayhi.common.event.ArticleEvent;
import com.yanwq.sayhi.common.tool.CropTool;
import com.yanwq.sayhi.common.tool.SharedPrefTool;
import com.yanwq.sayhi.controller.user.UserMgr;
import com.yanwq.sayhi.dao.bean.Article;
import com.yanwq.sayhi.dao.bean.Club;
import com.yanwq.sayhi.widget.MToast;

import java.io.File;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

public class PhotoAddActivity extends BaseToolbarActivity {

    @BindView(R.id.photo_summary)
    EditText mSummaryV;
    @BindView(R.id.photo_photo)
    ImageView mPhotoV;
    @BindView(R.id.photo_add)
    TextView mAddV;

    @OnClick(R.id.photo_add)
    public void pickPhoto(View v) {
        mCropTool.pick(this);
    }

    private File mPhotoFile;
    private String mFileName;
    private JSONObject mPhoto;
    private boolean hasPhoto;
    private CropTool mCropTool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_add);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_send, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        send();
        return true;
    }

    @Override
    public void init() {
        mFileName = CacheConstant.getRandomFileName();
        mPhotoFile = new File(CacheConstant.getPhotoPath(), mFileName);
        mCropTool = new CropTool();
    }

    @Override
    public void initView() {
        mToolbar.setTitle("发图片");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mCropTool.crop(mPhotoFile, this, requestCode, resultCode, data, new CropTool.CropCallback() {
            @Override
            public void onComplete(Uri resultUri) {
                mPhotoV.setImageURI(resultUri);
                hasPhoto = true;
                mAddV.setVisibility(View.GONE);
            }
        });
    }

    private void send() {
        if (!Pattern.matches(RegexConstant.summary, mSummaryV.getText().toString())) {
            MToast.showShort(PhotoAddActivity.this, "告诉大家你发的是什么");
            return;
        }

        if (!hasPhoto) {
            MToast.showShort(PhotoAddActivity.this, "你还没选图~");
            return;
        }

        if (mPhoto == null) {
            uploadPhoto();
        } else {
            sendPhoto();
        }
    }

    public void uploadPhoto() {
        OkRequestParams params = new OkRequestParams();
        params.put("mf", mFileName, mPhotoFile);

        OkRestClient.getInstance().post(this, "/oss/picture", params, new OkJsonObjectResponseCallback() {
            @Override
            public void onStart() {
                showProgressDialog("正在上传图片");
            }

            @Override
            public void onSuccess(JSONObject jsonObject) {
                mPhoto = jsonObject;
                sendPhoto();
            }

            @Override
            public void onFail(int status, String s, Throwable throwable) {
                super.onFail(status, s, throwable);
                cancelProgressDialog();
            }

            @Override
            public void onStop() {
            }
        });
    }

    public void sendPhoto() {
        Article article = new Article();
        article.setSummary(mSummaryV.getText().toString());
        article.setPhotoThumbUrl(mPhoto.getString("picThumbUrl"));
        article.setPhotoMediumUrl(mPhoto.getString("picMediumUrl"));
        article.setPhotoOriginUrl(mPhoto.getString("picOriginUrl"));
        article.setLon(0);
        article.setLat(0);
        article.setType(1);
        article.setPermission(0);

        article.setUser(UserMgr.get());

        String path = "/article/add";

        if (SharedPrefTool.getConfig("mode", "").equals("club")) {
            Club club = new Club();
            club.setId(SharedPrefTool.getConfig("clubId", 0));
            article.setClub(club);
            path = "/article/add/club";
        }

        OkRestClient.getInstance().post(this, path, article,
                new OkJsonObjectResponseCallback() {
                    @Override
                    public void onStart() {
                        showProgressDialog("正在发布");
                    }

                    @Override
                    public void onSuccess(JSONObject jsonObject) {
                        Article article = JSON.parseObject(jsonObject.toJSONString(),
                                Article.class);
                        MToast.showShort(PhotoAddActivity.this,
                                String.format("%s 发布成功", article.getSummary()));
                        delayFinish();

                        EventBus.getDefault().post(new ArticleEvent(
                                ArticleEvent.SEND_SUCCESS));
                    }

                    @Override
                    public void onStop() {
                        cancelProgressDialog();
                    }
                });
    }
}
